/**
 * 药品服务 API
 * 提供药品搜索、详情、分类等功能
 */

import { get, post, put, del } from './request.js'

class DrugService {
  
  /**
   * 搜索药品
   * @param {Object} params 搜索参数
   * @param {string} params.q 搜索关键词
   * @param {string} params.category 药品分类
   * @param {number} params.page 页码
   * @param {number} params.limit 每页数量
   * @param {string} params.sortBy 排序字段
   * @param {string} params.sortOrder 排序方向
   * @param {number} params.priceMin 最低价格
   * @param {number} params.priceMax 最高价格
   * @param {boolean} params.inStock 是否有库存
   * @returns {Promise}
   */
  async searchDrugs(params = {}) {
    try {
      console.log('[DrugService] 搜索药品:', params)
      
      const response = await get('/v1/drug/search', params, {
        showLoading: false
      })
      
      console.log('[DrugService] 搜索结果:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 搜索药品失败:', error)
      throw error
    }
  }

  /**
   * 获取药品详情
   * @param {string} drugId 药品ID
   * @returns {Promise}
   */
  async getDrugDetail(drugId) {
    try {
      console.log('[DrugService] 获取药品详情:', drugId)
      
      const response = await get(`/v1/drug/${drugId}`, {}, {
        showLoading: true
      })
      
      console.log('[DrugService] 药品详情:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 获取药品详情失败:', error)
      throw error
    }
  }

  /**
   * 获取药品分类统计
   * @returns {Promise}
   */
  async getDrugCategories() {
    try {
      console.log('[DrugService] 获取药品分类')
      
      const response = await get('/v1/drug/categories', {}, {
        showLoading: false
      })
      
      console.log('[DrugService] 药品分类:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 获取药品分类失败:', error)
      throw error
    }
  }

  /**
   * 获取热门药品
   * @param {number} limit 数量限制
   * @returns {Promise}
   */
  async getPopularDrugs(limit = 10) {
    try {
      console.log('[DrugService] 获取热门药品')
      
      const response = await get('/v1/drug/featured/popular', { limit }, {
        showLoading: false
      })
      
      console.log('[DrugService] 热门药品:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 获取热门药品失败:', error)
      throw error
    }
  }

  /**
   * 根据分类获取药品列表
   * @param {string} category 药品分类
   * @param {Object} options 其他选项
   * @returns {Promise}
   */
  async getDrugsByCategory(category, options = {}) {
    try {
      const params = {
        category,
        page: 1,
        limit: 20,
        inStock: true,
        ...options
      }
      
      return await this.searchDrugs(params)
      
    } catch (error) {
      console.error('[DrugService] 获取分类药品失败:', error)
      throw error
    }
  }

  /**
   * 药品名称联想搜索
   * @param {string} keyword 关键词
   * @returns {Promise}
   */
  async getSuggestions(keyword) {
    try {
      if (!keyword || keyword.trim().length === 0) {
        return { success: true, data: { drugs: [] } }
      }
      
      console.log('[DrugService] 获取搜索建议:', keyword)
      
      const response = await this.searchDrugs({
        q: keyword.trim(),
        limit: 10,
        inStock: true
      })
      
      // 返回药品名称列表，用于自动完成
      const suggestions = response?.data?.drugs?.map(drug => ({
        id: drug.drugId,
        name: drug.name,
        category: drug.category,
        price: drug.price
      })) || []
      
      return {
        success: true,
        data: { suggestions }
      }
      
    } catch (error) {
      console.error('[DrugService] 获取搜索建议失败:', error)
      return { success: true, data: { suggestions: [] } }
    }
  }

  /**
   * 创建药品（管理员功能）
   * @param {Object} drugData 药品数据
   * @returns {Promise}
   */
  async createDrug(drugData) {
    try {
      console.log('[DrugService] 创建药品:', drugData)
      
      const response = await post('/v1/drug', drugData, {
        showLoading: true
      })
      
      console.log('[DrugService] 药品创建成功:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 创建药品失败:', error)
      throw error
    }
  }

  /**
   * 更新药品（管理员功能）
   * @param {string} drugId 药品ID
   * @param {Object} drugData 药品数据
   * @returns {Promise}
   */
  async updateDrug(drugId, drugData) {
    try {
      console.log('[DrugService] 更新药品:', drugId, drugData)
      
      const response = await put(`/v1/drug/${drugId}`, drugData, {
        showLoading: true
      })
      
      console.log('[DrugService] 药品更新成功:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 更新药品失败:', error)
      throw error
    }
  }

  /**
   * 删除药品（管理员功能）
   * @param {string} drugId 药品ID
   * @returns {Promise}
   */
  async deleteDrug(drugId) {
    try {
      console.log('[DrugService] 删除药品:', drugId)
      
      const response = await del(`/v1/drug/${drugId}`, {
        showLoading: true
      })
      
      console.log('[DrugService] 药品删除成功:', response)
      return response
      
    } catch (error) {
      console.error('[DrugService] 删除药品失败:', error)
      throw error
    }
  }

  /**
   * 批量获取药品信息
   * @param {Array<string>} drugIds 药品ID数组
   * @returns {Promise}
   */
  async getBatchDrugs(drugIds) {
    try {
      console.log('[DrugService] 批量获取药品:', drugIds)
      
      const promises = drugIds.map(id => this.getDrugDetail(id))
      const responses = await Promise.allSettled(promises)
      
      const drugs = []
      responses.forEach((response, index) => {
        if (response.status === 'fulfilled' && response.value?.success) {
          drugs.push(response.value.data)
        } else {
          console.warn(`获取药品 ${drugIds[index]} 失败:`, response.reason)
        }
      })
      
      return {
        success: true,
        data: drugs
      }
      
    } catch (error) {
      console.error('[DrugService] 批量获取药品失败:', error)
      throw error
    }
  }

  /**
   * 检查药品库存
   * @param {string} drugId 药品ID
   * @returns {Promise}
   */
  async checkStock(drugId) {
    try {
      const response = await this.getDrugDetail(drugId)
      
      if (response?.success && response?.data) {
        return {
          success: true,
          data: {
            inStock: response.data.inStock,
            stockQuantity: response.data.stockQuantity || 0
          }
        }
      }
      
      return {
        success: false,
        message: '药品不存在'
      }
      
    } catch (error) {
      console.error('[DrugService] 检查库存失败:', error)
      throw error
    }
  }
}

// 创建服务实例
const drugService = new DrugService()

// 导出服务实例和类
export default drugService
export { DrugService }